package xuegao.study.mall.web.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xuegao.study.mall.web.domain.CartPromotionItem;
import xuegao.study.mall.common.domain.portal.PromotionProduct;
import xuegao.study.mall.web.service.OmsPromotionService;
import xuegao.study.mall.repo.dao.pms.PmsProductDao;
import xuegao.study.mall.common.model.oms.OmsCartItem;
import xuegao.study.mall.common.model.pms.PmsProductFullReduction;
import xuegao.study.mall.common.model.pms.PmsProductLadder;
import xuegao.study.mall.common.model.pms.PmsSkuStock;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 促销实现类
 */
@Service
public class OmsPromotionServiceImpl implements OmsPromotionService {

    @Autowired
    private PmsProductDao pmsProductDao;

    @Override
    public List<CartPromotionItem> calcCartPromotion(List<OmsCartItem> cartItemList) {
        // 1.先根据productId对OmsCartItem进行分组,以spu为单位计算优惠
        Map<Long, List<OmsCartItem>> productCartMap = cartItemList.stream().collect(Collectors.groupingBy(OmsCartItem::getProductId));
        // 2.查询所有商品的优惠相关信息
        List<PromotionProduct> promotionProductList = getPromotionProductList(cartItemList);
        // 3.根据商品促销类型,计算商品促销优惠价格
        List<CartPromotionItem> cartPromotionItemList = new ArrayList<>();
        for (Map.Entry<Long, List<OmsCartItem>> entry : productCartMap.entrySet()) {
            // 针对每一个商品ID进行计算相关的优惠
            Long productId = entry.getKey();
            PromotionProduct promotionProduct = promotionProductList.stream().filter(p -> p.getId().equals(productId)).findFirst().orElse(null);
            Integer promotionType = promotionProduct.getPromotionType();
            List<OmsCartItem> itemList = entry.getValue();
            switch (promotionType) {
                // 单品促销
                case 1:
                    handleSingProductPromotion(promotionProduct, itemList, cartPromotionItemList);
                    break;
                // 打折优惠
                case 3:
                    handleLadderPromotion(promotionProduct, itemList, cartPromotionItemList);
                    break;
                // 满减优惠
                case 4:
                    handleFullReductionPromotion(promotionProductList, promotionProduct, itemList, cartPromotionItemList);
                    break;
                // 无优惠
                default:
                    handleNoReduce(cartPromotionItemList, itemList, promotionProduct);
                    break;
            }
        }
        return cartPromotionItemList;
    }

    /**
     * 单品促销处理
     */
    private void handleSingProductPromotion(PromotionProduct promotionProduct, List<OmsCartItem> itemList, List<CartPromotionItem> cartPromotionItemList) {
        for (OmsCartItem item : itemList) {
            CartPromotionItem cartPromotionItem = new CartPromotionItem();
            BeanUtils.copyProperties(item, cartPromotionItem);
            cartPromotionItem.setPromotionMessage("单品促销");
            PmsSkuStock skuStock = promotionProduct.getSkuStockList().stream()
                    .filter(p -> p.getId().equals(item.getProductSkuId())).findFirst().orElse(null);
            BigDecimal originalPrice = skuStock.getPrice();
            cartPromotionItem.setPrice(originalPrice);
            cartPromotionItem.setReduceAmount(originalPrice.subtract(skuStock.getPromotionPrice()));// 减去金额=原价-促销价
            cartPromotionItem.setRealStock(skuStock.getStock() - skuStock.getLockStock());// 实际库存=总库存-锁定库存
            cartPromotionItem.setIntegration(promotionProduct.getGiftPoint());// 商品赠送的积分
            cartPromotionItem.setGrowth(promotionProduct.getGiftGrowth());// 商品赠送的成长值
            cartPromotionItemList.add(cartPromotionItem);
        }
    }

    /**
     * 打折优惠处理
     */
    private void handleLadderPromotion(PromotionProduct promotionProduct, List<OmsCartItem> itemList, List<CartPromotionItem> cartPromotionItemList) {
        // 获取购物车中商品的总数量
        int count = itemList.stream().mapToInt(OmsCartItem::getQuantity).sum();
        // 找出符合条件的打折优惠策略
        PmsProductLadder ladder = getProductLadder(count, promotionProduct.getProductLadderList());
        if (ladder != null) {
            for (OmsCartItem item : itemList) {
                CartPromotionItem cartPromotionItem = new CartPromotionItem();
                BeanUtils.copyProperties(item, cartPromotionItem);
                String message = getLadderPromotionMessage(ladder);
                cartPromotionItem.setPromotionMessage(message);
                PmsSkuStock skuStock = promotionProduct.getSkuStockList().stream()
                        .filter(p -> p.getId().equals(item.getProductSkuId())).findFirst().orElse(null);
                BigDecimal originalPrice = skuStock.getPrice();
                BigDecimal reduceAmount = originalPrice.subtract(ladder.getDiscount().multiply(originalPrice));
                cartPromotionItem.setReduceAmount(reduceAmount);
                cartPromotionItem.setRealStock(skuStock.getStock() - skuStock.getLockStock());// 实际库存=总库存-锁定库存
                cartPromotionItem.setIntegration(promotionProduct.getGiftPoint());// 商品赠送的积分
                cartPromotionItem.setGrowth(promotionProduct.getGiftGrowth());// 商品赠送的成长值
                cartPromotionItemList.add(cartPromotionItem);
            }
        } else {
            handleNoReduce(cartPromotionItemList, itemList, promotionProduct);
        }
    }

    /**
     * 根据商品数量获取满足条件的打折优惠策略
     */
    private PmsProductLadder getProductLadder(int count, List<PmsProductLadder> productLadderList) {
        // 数量从大大小排序
        productLadderList.sort((o1, o2) -> o2.getCount() - o1.getCount());
        for (PmsProductLadder productLadder : productLadderList) {
            if (count >= productLadder.getCount()) {
                return productLadder;
            }
        }
        return null;
    }

    /**
     * 打折优惠提示信息生成
     */
    private String getLadderPromotionMessage(PmsProductLadder ladder) {
        return "打折优惠：" +
                "满" +
                ladder.getCount() +
                "件，" +
                "打" +
                ladder.getDiscount().multiply(new BigDecimal(10)) +
                "折";
    }

    /**
     * 满减优惠
     */
    private void handleFullReductionPromotion(List<PromotionProduct> promotionProductList, PromotionProduct promotionProduct,
                                              List<OmsCartItem> itemList, List<CartPromotionItem> cartPromotionItemList) {
        // 计算购物车中该商品的总价
        BigDecimal totalAmount = getCartItemAmount(itemList, promotionProductList);
        // 找出符合条件的满减优惠策略
        PmsProductFullReduction fullReduction = getProductFullReduction(totalAmount, promotionProduct.getProductFullReductionList());
        if (fullReduction != null) {
            for (OmsCartItem item : itemList) {
                CartPromotionItem cartPromotionItem = new CartPromotionItem();
                BeanUtils.copyProperties(item, cartPromotionItem);
                String message = getFullReductionPromotionMessage(fullReduction);
                cartPromotionItem.setPromotionMessage(message);
                PmsSkuStock skuStock = getOriginalPrice(promotionProduct, item.getProductSkuId());
                BigDecimal originalPrice = skuStock.getPrice();
                // 满减是针对购物车中的所有商品,所以此处根据每件商品占价格的百分比分得优惠金额
                BigDecimal reduceAmount = originalPrice.divide(totalAmount, RoundingMode.HALF_EVEN).multiply(fullReduction.getReducePrice());
                cartPromotionItem.setReduceAmount(reduceAmount);
                cartPromotionItem.setRealStock(skuStock.getStock() - skuStock.getLockStock());
                cartPromotionItem.setIntegration(promotionProduct.getGiftPoint());
                cartPromotionItem.setGrowth(promotionProduct.getGiftGrowth());
                cartPromotionItemList.add(cartPromotionItem);
            }
        } else {
            handleNoReduce(cartPromotionItemList, itemList, promotionProduct);
        }
    }

    /**
     * 计算购物车中商品的总价
     */
    private BigDecimal getCartItemAmount(List<OmsCartItem> itemList, List<PromotionProduct> promotionProductList) {
        BigDecimal amount = new BigDecimal(0);
        for(OmsCartItem item : itemList) {
            PromotionProduct promotionProduct = getPromotionProductById(item.getProductId(), promotionProductList);
            PmsSkuStock skuStock = getOriginalPrice(promotionProduct, item.getProductSkuId());
            amount = amount.add(skuStock.getPrice()).multiply(new BigDecimal(item.getQuantity()));
        }
        return amount;
    }

    /**
     * 查找满减优惠策略
     */
    private PmsProductFullReduction getProductFullReduction(BigDecimal totalAmount, List<PmsProductFullReduction> productFullReductionList) {
        // 金额按照从高到低排序
        productFullReductionList.sort((o1, o2) -> o2.getFullPrice().subtract(o1.getFullPrice()).intValue());
        for (PmsProductFullReduction fullReduction : productFullReductionList) {
            if (totalAmount.subtract(fullReduction.getFullPrice()).intValue() >= 0) {
                return fullReduction;
            }
        }
        return null;
    }

    /**
     * 满减优惠提示信息生成
     */
    private String getFullReductionPromotionMessage(PmsProductFullReduction fullReduction) {
        StringBuilder sb = new StringBuilder();
        sb.append("满减优惠：");
        sb.append("满");
        sb.append(fullReduction.getFullPrice());
        sb.append("元，");
        sb.append("减");
        sb.append(fullReduction.getReducePrice());
        sb.append("元");
        return sb.toString();
    }


    /**
     * 无优惠策略的处理
     */
    private void handleNoReduce(List<CartPromotionItem> cartPromotionItemList, List<OmsCartItem> itemList, PromotionProduct promotionProduct) {
        for (OmsCartItem item : itemList) {
            CartPromotionItem cartPromotionItem = new CartPromotionItem();
            BeanUtils.copyProperties(item, cartPromotionItem);
            cartPromotionItem.setPromotionMessage("无优惠");
            cartPromotionItem.setReduceAmount(new BigDecimal(0));
            PmsSkuStock skuStock = getOriginalPrice(promotionProduct, item.getProductSkuId());
            if (skuStock != null) {
                cartPromotionItem.setRealStock(skuStock.getStock() - skuStock.getLockStock());
            }
            cartPromotionItem.setIntegration(promotionProduct.getGiftPoint());
            cartPromotionItem.setGrowth(promotionProduct.getGiftGrowth());
            cartPromotionItemList.add(cartPromotionItem);
        }
    }

    /**
     * 查询所有商品的优惠相关信息
     * @param cartItemList cartItemList
     * @return
     */
    private List<PromotionProduct> getPromotionProductList(List<OmsCartItem> cartItemList) {
        List<Long> productIdList = cartItemList.stream().map(OmsCartItem::getProductId).collect(Collectors.toList());
        return pmsProductDao.getPromotionProductList(productIdList);
    }

    /**
     * 根据商品id获取商品的促销信息
     */
    private PromotionProduct getPromotionProductById(Long productId, List<PromotionProduct> promotionProductList) {
        for (PromotionProduct promotionProduct : promotionProductList) {
            if (productId.equals(promotionProduct.getId())) {
                return promotionProduct;
            }
        }
        return null;
    }

    /**
     * 获取商品的原价
     */
    private PmsSkuStock getOriginalPrice(PromotionProduct promotionProduct, Long productSkuId) {
        for(PmsSkuStock skuStock : promotionProduct.getSkuStockList()) {
            if (productSkuId.equals(skuStock.getId())) {
                return skuStock;
            }
        }
        return null;
    }

}
